import React, { useState } from "react";
import {
  Card,
  Button,
  Input,
  Form,
  Avatar,
  Divider,
  Tag,
  Typography,
  Alert,
  message,
  Switch,
  Space,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  EditOutlined,
  SaveOutlined,
  ReloadOutlined,
  LogoutOutlined,
} from "@ant-design/icons";
import { useUserStore } from "../stores/userStore";
import authService from "../services/auth";

const { Title, Paragraph, Text } = Typography;

interface LoginFormValues {
  username: string;
  password: string;
}

const UserInfoDemo: React.FC = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [formEdit] = Form.useForm();

  // 直接从Zustand获取状态
  const user = useUserStore();

  // 登录处理
  const handleLogin = async (values: LoginFormValues) => {
    try {
      setLoading(true);
      await authService.login(values.username, values.password);
      messageApi.success("登录成功！");
    } catch (error) {
      messageApi.error("登录失败: " + (error as Error).message);
    } finally {
      setLoading(false);
    }
  };

  // 退出登录
  const handleLogout = () => {
    authService.logout();
    messageApi.success("已退出登录");
  };

  // 更新用户信息
  const handleUpdateUser = (values: any) => {
    authService.updateUserInfo(values);
    setEditMode(false);
    messageApi.success("用户信息已更新");
  };

  // 进入编辑模式
  const enableEditMode = () => {
    formEdit.setFieldsValue({
      username: user.username,
      email: user.email || "",
    });
    setEditMode(true);
  };

  // 添加测试权限
  const handleAddTestPermission = () => {
    const currentPermissions = [...user.permissions];
    const newPermission = "test:special-access";

    if (!currentPermissions.includes(newPermission)) {
      authService.updateUserInfo({
        permissions: [...currentPermissions, newPermission],
      });
      messageApi.success(`已添加测试权限: ${newPermission}`);
    } else {
      messageApi.info("已拥有该权限");
    }
  };

  return (
    <div className="user-store-demo">
      {contextHolder}

      <Card className="main-card">
        <Title level={3}>用户信息持久化演示</Title>
        <Paragraph type="secondary">
          基于Zustand的用户状态管理，包含持久化存储和身份验证
        </Paragraph>

        <Divider />

        {!user.isAuthenticated ? (
          // 未登录状态 - 显示登录表单
          <Card title="用户登录" bordered={false}>
            <Form
              form={form}
              name="loginForm"
              layout="vertical"
              onFinish={handleLogin}
              initialValues={{ username: "admin", password: "password" }}
            >
              <Form.Item
                name="username"
                rules={[{ required: true, message: "请输入用户名" }]}
              >
                <Input
                  prefix={<UserOutlined />}
                  placeholder="用户名 (admin 或 user)"
                />
              </Form.Item>

              <Form.Item
                name="password"
                rules={[{ required: true, message: "请输入密码" }]}
              >
                <Input.Password
                  prefix={<LockOutlined />}
                  placeholder="密码 (password)"
                />
              </Form.Item>

              <Button type="primary" htmlType="submit" block loading={loading}>
                登录
              </Button>
            </Form>

            <Alert
              style={{ marginTop: 16 }}
              message="测试账号"
              description={
                <>
                  <div>管理员：admin / password</div>
                  <div>普通用户：user / password</div>
                </>
              }
              type="info"
              showIcon
            />
          </Card>
        ) : (
          // 已登录状态 - 显示用户信息
          <>
            {!editMode ? (
              <Card
                title="当前用户信息"
                bordered={false}
                extra={
                  <Button
                    type="text"
                    icon={<EditOutlined />}
                    onClick={enableEditMode}
                  >
                    编辑
                  </Button>
                }
              >
                <div className="user-profile">
                  <div className="user-avatar">
                    <Avatar
                      size={64}
                      icon={<UserOutlined />}
                      src={user.avatar}
                      style={{ backgroundColor: "#1677ff" }}
                    />
                  </div>

                  <div className="user-details">
                    <div className="user-name">
                      <Text strong style={{ fontSize: 18 }}>
                        {user.username}
                      </Text>
                      {user.lastLogin && (
                        <Text
                          type="secondary"
                          style={{ fontSize: 12, marginLeft: 8 }}
                        >
                          上次登录: {new Date(user.lastLogin).toLocaleString()}
                        </Text>
                      )}
                    </div>

                    <div className="user-email">
                      {user.email ? (
                        user.email
                      ) : (
                        <Text type="secondary">未设置邮箱</Text>
                      )}
                    </div>

                    <div className="user-roles">
                      角色:&nbsp;
                      {user.roles.map((role) => (
                        <Tag color="blue" key={role}>
                          {role}
                        </Tag>
                      ))}
                    </div>

                    <div className="user-permissions">
                      权限:&nbsp;
                      {user.permissions.map((permission) => (
                        <Tag color="green" key={permission}>
                          {permission}
                        </Tag>
                      ))}
                      <Button
                        type="link"
                        size="small"
                        onClick={handleAddTestPermission}
                      >
                        添加测试权限
                      </Button>
                    </div>
                  </div>
                </div>

                <div className="auth-info">
                  <div className="auth-status">
                    <div>
                      认证状态:{" "}
                      <Switch checked={user.isAuthenticated} disabled />
                    </div>
                    {user.token && (
                      <div>
                        Token:{" "}
                        <Text code ellipsis>
                          {user.token}
                        </Text>
                      </div>
                    )}
                  </div>

                  <Button
                    danger
                    icon={<LogoutOutlined />}
                    onClick={handleLogout}
                  >
                    退出登录
                  </Button>
                </div>
              </Card>
            ) : (
              <Card
                title="编辑用户信息"
                bordered={false}
                extra={
                  <Button type="text" onClick={() => setEditMode(false)}>
                    取消
                  </Button>
                }
              >
                <Form
                  form={formEdit}
                  name="editUserForm"
                  layout="vertical"
                  onFinish={handleUpdateUser}
                >
                  <Form.Item
                    name="username"
                    label="用户名"
                    rules={[{ required: true, message: "请输入用户名" }]}
                  >
                    <Input />
                  </Form.Item>

                  <Form.Item
                    name="email"
                    label="电子邮箱"
                    rules={[{ type: "email", message: "请输入有效的邮箱地址" }]}
                  >
                    <Input />
                  </Form.Item>

                  <Form.Item name="avatar" label="头像URL">
                    <Input placeholder="输入头像图片URL" />
                  </Form.Item>

                  <Space>
                    <Button
                      type="primary"
                      icon={<SaveOutlined />}
                      htmlType="submit"
                    >
                      保存修改
                    </Button>
                    <Button
                      icon={<ReloadOutlined />}
                      onClick={() => setEditMode(false)}
                    >
                      取消
                    </Button>
                  </Space>
                </Form>
              </Card>
            )}

            <Card
              title="状态检查器"
              size="small"
              style={{ marginTop: 16 }}
              bodyStyle={{ padding: 0 }}
            >
              <pre className="state-inspector">
                {JSON.stringify(user, null, 2)}
              </pre>
            </Card>
          </>
        )}
      </Card>
    </div>
  );
};

export default UserInfoDemo;
